package com.mz.ozy.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.mz.ozy.R;
import com.mz.ozy.activity.assets.ExchangeActivity;
import com.mz.ozy.activity.shop.CommentActivity;
import com.mz.ozy.activity.shop.ExchangeOrderActivity;
import com.mz.ozy.adapter.ShopDetailAdapter;
import com.mz.ozy.adapter.ShopDetailBannerAdapter;
import com.mz.ozy.adapter.ShopEvaluateAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.ExchangeOrderBean;
import com.mz.ozy.bean.GoodsImgBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.ShopDetailBean;
import com.mz.ozy.bean.ShopSpecListBean;
import com.mz.ozy.mvp.presenter.ExchangeDetailPresenter;
import com.mz.ozy.mvp.presenter.ScheduledDetailPresenter;
import com.mz.ozy.mvp.view.ExchangeDetailContract;
import com.mz.ozy.mvp.view.ScheduledDetailContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.ScreenUtil;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.ExchangeSpecDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

public class ScheduledDetailActivity extends BaseActivity<ScheduledDetailContract.View, ScheduledDetailPresenter> implements ScheduledDetailContract.View, ViewPager.OnPageChangeListener {
    @BindView(R.id.rollPagerView)
    RollPagerView mRollPagerView;
    @BindView(R.id.tv_goods_price)
    TextView mTvPrice;
    @BindView(R.id.shopDetail)
    TextView mTvShopDetail;
    @BindView(R.id.tv_shop_desc)
    TextView mTvShopDesc;
    @BindView(R.id.tv_goods_unit)
    TextView mTvGoodsUnitBv;
    @BindView(R.id.tv_unit_price)
    TextView mTvUnitPrice;
    @BindView(R.id.tv_choose_rules)
    TextView mTvChooseRules;
    @BindView(R.id.tv_select_rules)
    TextView mTvSelectRules;
    @BindView(R.id.rv_shop_detail)
    RecyclerView mRvShopDetail;
    @BindView(R.id.tv_rollpager_hint)
    TextView mTvRollpagerHint;
    @BindView(R.id.rv_food_evaluate)
    RecyclerView mRvFoodEvaluate;
    @BindView(R.id.iv_shop_info_star)
    ImageView mIvShopInfoStar;

    @BindView(R.id.tv_user_evaluation)
    TextView mTvUserEvaluate;
    @BindView(R.id.tv_view_reviews)
    TextView mTvReviews;
    @BindView(R.id.tv_shop_about)
    TextView mTvShopAbout;
    @BindView(R.id.tv_detail_parameter)
    TextView mTvDetailParameter;
    @BindView(R.id.ll_detail_parameter)
    LinearLayout mLlDetailParameter;

    private ShopEvaluateAdapter mEvaluateAdapter;
    private ShopDetailBannerAdapter mBannerAdapter;
    private ShopDetailAdapter mDetailAdapter;
    private ExchangeSpecDialog mSpecPopupWindow;
    private ShopDetailBean.ShopMapBean bean;
    private List<GoodsImgBean> mGoodsImgListBeans = new ArrayList<>();
    private String goodsId;
    private ShopSpecListBean mSpecListBeans;
    private int mPosition = 0;
    private boolean comEmpty = false;
    private String attribute;
    private boolean isFirstResume = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheduled_detail);
        ButterKnife.bind(this);
        initTitle();
        QMUIStatusBarHelper.translucent(this);
        setTitleBarMargin();
        mRollPagerView.setAnimationDurtion(500);
        mRollPagerView.setPlayDelay(-1);
        mRollPagerView.setHintView(null);
        mBannerAdapter = new ShopDetailBannerAdapter(this, mGoodsImgListBeans);
        mRollPagerView.setAdapter(mBannerAdapter);
        goodsId = getIntent().getStringExtra("goodsId");
        attribute = getIntent().getStringExtra("attribute");

        mTvChooseRules.setText("已选择");
        mTvSelectRules.setText(attribute);
        mDetailAdapter = new ShopDetailAdapter(null);
        mRvShopDetail.setLayoutManager(new LinearLayoutManager(this));
        mRvShopDetail.setAdapter(mDetailAdapter);
        mRvShopDetail.setNestedScrollingEnabled(false);
        mRollPagerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                Intent intent = new Intent(ShopDetailActivity.this, PhotoViewActivity.class);
//                intent.putExtra("url", mGoodsImgListBeans.get(position).getImg_zt());
//                startActivity(intent);
            }
        });
        mRollPagerView.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                final int index = position + 1;
                String hint = index + "/" + mBannerAdapter.getCount();
                mTvRollpagerHint.setText(hint);
                if (position != 0) {
                    mBannerAdapter.setPause(true);
                } else {
                    mBannerAdapter.setPause(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mIvShopInfoStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.onGoodsFollow(ScheduledDetailActivity.this, goodsId);
            }
        });

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);//把布局设为横行排列
        mRvFoodEvaluate.setLayoutManager(layoutManager1);
        mEvaluateAdapter = new ShopEvaluateAdapter(null);
        mRvFoodEvaluate.setAdapter(mEvaluateAdapter);

        mPresenter.obtainShopDetailInfo(this, goodsId);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!isFirstResume) {
//            if (mBannerAdapter != null) {
//                mBannerAdapter.setPause(false);
//            }
//        }
//        isFirstResume = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBannerAdapter != null) {
            mBannerAdapter.setPause(true);
        }
        Jzvd.resetAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mWebView.destroy();
//        EventBus.getDefault().unregister(this);

    }


    @Override
    public void obtainShopDetailInfoSuccess(ShopDetailBean detailBean) {
        if (detailBean.getIsCon() == 0) {
            mIvShopInfoStar.setImageResource(R.mipmap.icon_detail_collect);
        } else {
            mIvShopInfoStar.setImageResource(R.mipmap.icon_detail_select);
        }
        final ShopDetailBean.BMapBean bMapBean = detailBean.getbMap();
        if (bMapBean != null) {
            mTvShopAbout.setText(bMapBean.getAbout());
        } else {
            mTvShopAbout.setText("");
        }
        mTvUserEvaluate.setText("用户评价（" + detailBean.getComNum() + "）");
        if (detailBean.getComNum() == 0) {
            comEmpty = true;
            mTvReviews.setText("该商品暂无评价");
            mTvReviews.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        } else {
            comEmpty = false;
            mTvReviews.setText("查看" + detailBean.getComNum() + "条评价");
        }
        final List<ShopDetailBean.ComListBean> comList = detailBean.getComList();
        if (comList != null && comList.size() > 0) {
            mEvaluateAdapter.setNewData(comList);
        } else {
            mRvFoodEvaluate.setVisibility(View.GONE);
        }
        final ShopDetailBean.ShopMapBean map = detailBean.getMap();
        if (map != null) {
            bean = map;
            mGoodsImgListBeans.clear();
            if (!TextUtils.isEmpty(bean.getVido())) {
                mGoodsImgListBeans.add(new GoodsImgBean(bean.getVido(), 1));
            }
            if (!TextUtils.isEmpty(bean.getImg_zt())) {
                final String[] imgZtArr = bean.getImg_zt().trim().split(",");
                for (String imgPath : imgZtArr) {
                    mGoodsImgListBeans.add(new GoodsImgBean(imgPath, 0));
                }
            }
            if (mGoodsImgListBeans.size() > 0) {
                mTvRollpagerHint.setText("1/" + mGoodsImgListBeans.size());
            }
            mBannerAdapter.notifyDataSetChanged();
//            mRollPagerView.pause();
            if (!TextUtils.isEmpty(bean.getImg_xq())) {
                final String[] imgXqArr = bean.getImg_xq().trim().split(",");
                final List<String> imgList = Arrays.asList(imgXqArr);
                mDetailAdapter.setNewData(imgList);
            }
            mTvShopDetail.setText(bean.getTradename());
            mTvShopDesc.setText(bean.getDescribed());

            String price = getPrice();
            mTvPrice.setText(price);
            if (Double.parseDouble(bean.getShopbv()) == 0.00) {
                mTvGoodsUnitBv.setText("");
            } else {
                mTvGoodsUnitBv.setText("(" + bean.getShopbv() + "BV)");
            }
            mTvUnitPrice.setText(bean.getWeight() + "g");

            final List<ShopDetailBean.ParameterBean> parameterBeans = detailBean.getcList();
            if (parameterBeans == null || parameterBeans.size() == 0) {
                mTvDetailParameter.setVisibility(View.GONE);
                mLlDetailParameter.setVisibility(View.GONE);
            } else {
                for (ShopDetailBean.ParameterBean parameterBean : parameterBeans) {
                    final View submitOrderView = View.inflate(this, R.layout.item_goods_parameter, null);
                    processParameterView(submitOrderView, parameterBean);
                }
            }
        }
    }

    private void processParameterView(View submitOrderView, ShopDetailBean.ParameterBean parameterBean) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLlDetailParameter.addView(submitOrderView, params);
        TextView tvCvName = submitOrderView.findViewById(R.id.tv_cv_name);
        tvCvName.setText(parameterBean.getCname());
        TextView tvCvValue = submitOrderView.findViewById(R.id.tv_cv_value);
        tvCvValue.setText(parameterBean.getCvalue());
    }

    @NotNull
    private String getPrice() {
        String price = "";
        if (!TextUtils.isEmpty(bean.getPrice()) && Double.parseDouble(bean.getPrice()) != 0.00) {
            price += "¥";
            price += bean.getPrice();
        }
        if (!TextUtils.isEmpty(bean.getMarket_price()) && Double.parseDouble(bean.getMarket_price()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += bean.getMarket_price();
                price += "积分";
            } else {
                price += bean.getMarket_price();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    @Override
    public void obtainSpecListSuccess(ShopSpecListBean listBean) {
        mSpecListBeans = listBean;
        String mainImg = "";
        if (mGoodsImgListBeans != null && mGoodsImgListBeans.size() > 0) {
            GoodsImgBean goodsImgBean = mGoodsImgListBeans.get(0);
            if (goodsImgBean.getType() == 1) {
                goodsImgBean = mGoodsImgListBeans.get(1);
            }
            mainImg = goodsImgBean.getImgPath();
        }
        mSpecListBeans.setGoodsImg(mainImg);
        showSpecPopWindow();
    }

    @OnClick({R.id.rl_user_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user_comment:
                if (!comEmpty) {
                    Intent intent = new Intent(this, CommentActivity.class);
                    intent.putExtra(CommentActivity.TYPE_CID, goodsId);
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 显示规格判断
     */
    public void showSpecView() {
        if (mSpecPopupWindow != null) {
            showSpecPopWindow();
        } else {
            mPresenter.obtainSpecList(this, goodsId);
        }
    }


    public void showSpecPopWindow() {
        mSpecPopupWindow = new ExchangeSpecDialog(this, mSpecListBeans, mPosition, new ExchangeSpecDialog.OnClickListener() {
            @Override
            public void onSubmit(int ggId, String name, int type, int position) {
                mPosition = position;
                mTvChooseRules.setText("已选择");
                mTvSelectRules.setVisibility(View.VISIBLE);
                mTvSelectRules.setText(name);
                if (type == 1) {
                    mPresenter.onBuy(ScheduledDetailActivity.this, goodsId, ggId + "");
                }
            }

        });
        mSpecPopupWindow.show(getSupportFragmentManager(), "goods");
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        if ("1075".equals(bean.getRespCode())) {
            final BaseDialog dialog = new BaseDialog(ScheduledDetailActivity.this, R.layout.dialog_private, Gravity.CENTER, true);
            ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("请提交您的兑换券码");
            ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("兑换券");
            ((TextView) dialog.getView(R.id.btn_confirm)).setText("去兑换");
            dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.toggleDialog();
                }
            });
            dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(ScheduledDetailActivity.this, ExchangeActivity.class));
                    dialog.toggleDialog();
                }
            });
            dialog.toggleDialog();
        } else {
            super.handleFailResponse(bean);
        }
    }

    /**
     * 立即购买
     *
     * @param
     */
    @Override
    public void onBuySuccess(ExchangeOrderBean orderBean) {
        if (mSpecPopupWindow != null && mSpecPopupWindow.isVisible()) {
            mSpecPopupWindow.dismiss();
        }
//        ExchangeOrderActivity.start(this, orderBean, goodsId);
    }

    @Override
    public void onGoodsFollowSuccess(Object o) {
        mPresenter.obtainShopDetailInfo(this, goodsId);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}
